package cn.tedu.medicalmanagementsystem.user.controller;
import cn.tedu.medicalmanagementsystem.base.response.JsonResult;
import cn.tedu.medicalmanagementsystem.base.response.StatusCode;
import cn.tedu.medicalmanagementsystem.user.mapper.UserMapper;
import cn.tedu.medicalmanagementsystem.user.pojo.dto.*;
import cn.tedu.medicalmanagementsystem.user.pojo.entity.User;
import cn.tedu.medicalmanagementsystem.user.pojo.vo.UserVO;
import cn.tedu.medicalmanagementsystem.user.service.UserLoginService;
import cn.tedu.medicalmanagementsystem.user.service.UserService;
import cn.tedu.medicalmanagementsystem.user.service.UserService1;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/v1/user")
@Api(tags = "用户模块")

public class UserController {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private UserService1 userService1;

    @Autowired
    private UserLoginService userLoginService;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    @ApiOperation("用户注册")
    @ApiOperationSupport(order = 10)
    public JsonResult register(@RequestBody @Validated UserRegisterParam userRegisterParam) {
        log.debug("开始处理用户注册请求，参数：{}", userRegisterParam);

        // 检查 username 是否已存在
        String username = userRegisterParam.getUsername();
        if (userMapper.usernameExists(username) > 0) {
            return new JsonResult(StatusCode.USERNAME_EXISTS);
        }

        // 检查 phone 是否已存在
        String phone = userRegisterParam.getPhone();
        if (userMapper.phoneExists(phone) > 0) {
            return new JsonResult(StatusCode.PHONE_EXISTS);
        }

        // 检查 email 是否已存在
        String email = userRegisterParam.getEmail();
        if (userMapper.emailExists(email) > 0) {
            return new JsonResult(StatusCode.EMAIL_EXISTS);
        }

        // 创建 User 实例
        User user = new User();
        BeanUtils.copyProperties(userRegisterParam, user); // 使用 BeanUtils 自动复制属性

//        // 手动检查并转换性别字段
//        String gender = userRegisterParam.getGender();
//        if ("男".equals(gender)) {
//            user.setGender("male");
//        } else if ("女".equals(gender)) {
//            user.setGender("female");
//        } else {
//            user.setGender("male"); // 默认值
//        }

        // 手动转换 birthday 字段
//        if (userRegisterParam.getBirthday() != null) {
//            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//            LocalDate localDate = LocalDate.parse(userRegisterParam.getBirthday(), formatter);
//            LocalDateTime localDateTime = localDate.atStartOfDay(); // 转换为 LocalDateTime
//            user.setBirthday(localDateTime);
//        }

        // 转换生日为 LocalDateTime
        if (userRegisterParam.getBirthday() != null) {
            user.setBirthday(userRegisterParam.getBirthday().atStartOfDay());
        }
        // 设置创建时间
        //user.setCreateTime(LocalDateTime.now());
        user.setCreateTime(LocalDateTime.now());
        log.debug("准备插入用户信息: {}", user);
        userMapper.insert(user);

        return JsonResult.ok("注册成功");
    }

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public JsonResult<UserVO> login(@RequestBody @Valid UserLoginParam userLoginParam, HttpSession session) {
        JsonResult<UserVO> result = userLoginService.login(userLoginParam);
        if (result.getState() == StatusCode.OPERATION_SUCCESS.getState()) {
            System.out.println("登录成功，用户信息: " + result.getData()); // ✅ 打印数据
            session.setAttribute("user", result.getData());
        }
        return result;
    }
    /**
     * 修改个人信息
     */
    @PostMapping("/updateOwn")
    @ApiOperation("修改个人信息")
    @ApiOperationSupport(order = 20)
    public JsonResult update(@RequestBody UserUpdateParam userUpdateParam,
                             HttpSession session) {
        log.debug("开始处理修改个人信息请求，参数：{}", userUpdateParam);
        // 从session中获取当前用户
        UserVO currentUser = (UserVO) session.getAttribute("user");
        if (currentUser == null) {
            return new JsonResult(StatusCode.NOT_LOGIN);
        }

        // 设置当前用户ID到更新参数中
        userUpdateParam.setUserId(currentUser.getId());

        // 调用服务层更新用户信息
        JsonResult result = userService1.updateUser(userUpdateParam);

        // 如果更新成功，刷新session中的用户信息
        if (result.getState() == StatusCode.OPERATION_SUCCESS.getState()) {
            try {
                UserVO updatedUser = userLoginService.getUserById(currentUser.getId());
                if (updatedUser != null) {
                    session.setAttribute("user", updatedUser);
                    log.debug("用户session信息已更新，用户ID：{}", currentUser.getId());
                }
            } catch (Exception e) {
                log.error("刷新用户session信息失败，用户ID：{}，异常：{}",
                        currentUser.getId(), e.getMessage());
                // 不返回错误，因为主要操作已成功完成
            }
        }

        return result;
    }

//    @PostMapping("/updatePassword")
//    @ApiOperation("修改密码")
//    public JsonResult updatePassword(@RequestBody @Validated UserUpdatePasswordParam userUpdatePasswordParam,
//                                     HttpSession session) {
//        log.debug("开始处理修改密码请求，参数：{}", userUpdatePasswordParam);
//        // 从session中获取当前用户
//        UserVO currentUser = (UserVO) session.getAttribute("user");
//        if (currentUser == null) {
//            return new JsonResult(StatusCode.NOT_LOGIN);
//        }
//
//        // 设置当前用户ID到更新参数中
//        userUpdatePasswordParam.setUserId(currentUser.getId());
//        JsonResult result = userService1.updatePassword(userUpdatePasswordParam);
//                                     }

    @GetMapping("/info")
    @ApiOperation("获取当前登录用户信息")
    public JsonResult<UserVO> getCurrentUserInfo(HttpSession session) {

        UserVO user = (UserVO) session.getAttribute("user");
        if (user == null) {
            return new JsonResult(StatusCode.NOT_LOGIN, "用户未登录"); // 返回 401 状态码
        }
        return JsonResult.success(user);

    }
    @PostMapping("/logout")
    @ApiOperation("用户登出")
    @ApiOperationSupport(order = 40)
    public JsonResult logout(HttpSession session) {
        session.removeAttribute("user");
        return JsonResult.ok();
    }

    @GetMapping("/countsAppointment")
    @ApiOperation("统计用户预约数量")
    public JsonResult<Integer> countsAppointment(HttpSession session) {
        UserVO user = (UserVO) session.getAttribute("user");
        if (user == null) {
            return new JsonResult(StatusCode.NOT_LOGIN, "用户未登录"); // 返回 401 状态码
        }
        return JsonResult.success(userMapper.countsAppointment(user.getId()));
    }

    @GetMapping("/countsReview")
    @ApiOperation("统计用户评价数量")
    public JsonResult<Integer> countsReview(HttpSession session) {
        UserVO user = (UserVO) session.getAttribute("user");
        if (user == null) {
            return new JsonResult(StatusCode.NOT_LOGIN, "用户未登录"); // 返回 401 状态码
        }
        return JsonResult.success(userMapper.countsReview(user.getId()));
    }

    @GetMapping("/countsFavorite")
    @ApiOperation("统计用户收藏数量")
    public JsonResult<Integer> countsPavorite(HttpSession session) {
        UserVO user = (UserVO) session.getAttribute("user");
        if (user == null) {
            return new JsonResult(StatusCode.NOT_LOGIN, "用户未登录"); // 返回 401 状态码
        }
        return JsonResult.success(userMapper.countsFavorite(user.getId()));
    }
}

